<template>
    <div class="person-center">
        <a-tabs v-model:activeKey="activeKey" :tab-position="tabPosition" animated>
            <a-tab-pane key="3" tab="用户信息">
                <div class="top-title">
                    <span>用户信息</span>
                </div>
                <div class="user-info-content">
                    <div class="user-info">
                        <a-form ref="formRef1" :model="formState" :rules="rulesUserInfo" :label-col="labelCol"
                            :wrapper-col="wrapperCol">
                            <a-form-item ref="name" label="用户名" name="userName">
                                <a-input v-model:value="formState.userName" disabled />
                            </a-form-item>
                            <a-form-item ref="name" label="昵称" name="nickName">
                                <a-input v-model:value="formState.nickName" />
                            </a-form-item>
                            <a-form-item label="性别" name="sex">
                                <a-radio-group v-model:value="formState.sex">
                                    <a-radio :value="0">男</a-radio>
                                    <a-radio :value="1">女</a-radio>
                                </a-radio-group>
                            </a-form-item>
                            <a-form-item label="备注" name="remark">
                                <a-textarea v-model:value="formState.remark" />
                            </a-form-item>
                            <a-form-item :wrapper-col="btn_wrapper_col">
                                <a-button class="submit-btn" type="primary" @click="handleSaveUserInfo()">保存</a-button>
                            </a-form-item>
                        </a-form>
                    </div>

                    <div class="user-avatar">
                        <a-avatar :size="100">
                            <template #icon>
                                <AntDesignOutlined />
                            </template>
                        </a-avatar>
                    </div>
                </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="重置密码">
                <div class="top-title">
                    <span>重置密码</span>
                </div>
                <div class="reset-password">
                    <a-form ref="formRef2" :model="resetPwdForm" :rules="rules" :label-col="labelCol1"
                        :wrapper-col="wrapperCol">
                        <a-form-item ref="password" label="密码" name="password">
                            <a-input-password v-model:value="resetPwdForm.password" />
                        </a-form-item>
                        <a-form-item ref="confirmPassword" label="确认密码" name="confirmPassword">
                            <a-input-password v-model:value="resetPwdForm.confirmPassword" />
                        </a-form-item>
                        <a-form-item :wrapper-col="btn_wrapper_col">
                            <a-button class="submit-btn" type="primary" @click="handleResetPwd">确定</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </a-tab-pane>
        </a-tabs>
    </div>
</template>

<script setup>
import { getUserInfo, updatePassword, logout, updateUserInfo } from "@/api/user";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { Modal, message } from "ant-design-vue";
import { createVNode, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/user";

const router = useRouter();
const userStore = useUserStore();

const validatePass = async (_rule, value) => {
    if (value === '') {
        passValidateFlag.value = false;
        return Promise.reject('请输入密码');
    } else {
        if (!validatePassword(value)) {
            passValidateFlag.value = false;
            return Promise.reject('由数字，小写字母，大写字母和字符中的任意二种组成，且长度不小于8位。');
        }
        passValidateFlag.value = true;
        return Promise.resolve();
    }
};
const validatePass2 = async (_rule, value) => {
    if (value === '') {
        passValidateFlag1.value = false;
        return Promise.reject('请再次输入密码');
    } else if (value !== resetPwdForm.password) {
        passValidateFlag1.value = false;
        return Promise.reject("两次输入的密码不一致");
    } else {
        passValidateFlag1.value = true;
        return Promise.resolve();
    }
};


const validatePassword = (password) => {
    // 至少8位长度检查
    if (password.length < 8) return false;

    // 定义四种字符类型的正则
    const hasNumber = /\d/.test(password);          // 包含数字
    const hasLower = /[a-z]/.test(password);        // 包含小写字母
    const hasUpper = /[A-Z]/.test(password);        // 包含大写字母
    const hasSpecial = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password); // 包含特殊字符

    // 统计满足的字符类型数量
    const conditionsMet = [hasNumber, hasLower, hasUpper, hasSpecial]
        .filter(Boolean).length;

    // 至少满足两种类型
    return conditionsMet >= 2;
}

const rules = {
    password: [
        {
            required: true,
            validator: validatePass,
            trigger: 'change',
        },
    ],
    confirmPassword: [
        {
            required: true,
            validator: validatePass2,
            trigger: 'change',
        },
    ],
};
const rulesUserInfo = {
    userName: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'change',
        },
    ],
    nickName: [
        {
            required: true,
            message: '昵称不能为空',
            trigger: 'change',
        },
    ],
};

onMounted(() => {
    getUserInfo().then((res) => {
        if (res.code === 200 && res.data) {
            console.log("res.data", res.data);
            let data = res.data;
            formState.nickName = data.nickName;
            formState.userName = data.userName;
            formState.sex = data.sex;
            formState.remark = data.remark;
        }
    });
})

// tab 切换位置
const tabPosition = ref("left");

const wrapperCol = reactive({
    span: 14,
    offset: 0,
});
// 按钮偏移量
const btn_wrapper_col = reactive({
    offset: 5,
});
// 标签宽度
const labelCol = {
    style: {
        width: '90px',
    },
};
const labelCol1 = {
    style: {
        width: '86px',
    },
};

const resetPwdForm = reactive({
    password: "",
    confirmPassword: "",
});

const formState = reactive({
    sex: "",
    remark: "",
    userName: "",
    nickName: "",
});

const formRef1 = ref(null);
const formRef2 = ref(null);

const passValidateFlag = ref(false);
const passValidateFlag1 = ref(false);
// 更新密码
const handleResetPwd = () => {
    try {
        formRef2.value.validateFields();
        if (passValidateFlag.value && passValidateFlag1.value) {
            Modal.confirm({
                title: '确定要修改密码吗？',
                icon: createVNode(ExclamationCircleOutlined),
                content: createVNode(
                    'div',
                    {
                        style: 'color:red;',
                    },
                    '修改后需要重新登录，请牢记新密码',
                ),
                okText: '确定',
                cancelText: '取消',
                onOk() {
                    updatePassword(resetPwdForm).then((res) => {
                        if (res.code === 200) {
                            localStorage.removeItem('userName');
                            localStorage.removeItem('nickName');
                            localStorage.removeItem('password');
                            localStorage.removeItem('remember');
                            localStorage.removeItem('token');
                            router.push("/login");
                        }
                    });
                },
                onCancel() {
                },
                class: 'updatePwd',
            });
        }
    } catch (error) {
        console.log('验证失败:', error);
    }
}
// 保存用户信息
const handleSaveUserInfo = () => {
    console.log(formState);
    updateUserInfo(formState).then((res) => {
        if (res.code === 200) {
            message.success("保存成功");
            userStore.setNickName(formState.nickName);
        }
    });
}
</script>

<style lang="scss">
.person-center {
    background-color: #fff;
    width: 100%;
    min-width: 680px;

    .top-title {
        border-bottom: 1px solid rgb(230, 227, 227);
        display: flex;
        height: 50px;
        align-items: center;
        padding-left: 15px;
        margin-bottom: 10px;
        font-weight: 600;
    }

    .user-info-content {
        padding: 10px;
        display: flex;

        .user-info {
            min-width: 430px;
        }

        .user-avatar {
            width: 55%;
            display: flex;
            justify-content: center;
            padding-top: 60px;
        }
    }

    .reset-password {
        padding: 10px;
        width: 430px;
    }

    .submit-btn {
        background-color: #4ab44a;

        &:hover {
            background-color: #498f45;
            border: 1px solid #7ed37a;
        }
    }

    :where(.css-dev-only-do-not-override-1p3hq3p).ant-tabs-left>.ant-tabs-content-holder>.ant-tabs-content>.ant-tabs-tabpane,
    :where(.css-dev-only-do-not-override-1p3hq3p).ant-tabs-left>div>.ant-tabs-content-holder>.ant-tabs-content>.ant-tabs-tabpane {
        padding-left: 0;
    }

    :where(.css-dev-only-do-not-override-1p3hq3p).ant-tabs .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
        color: #0a7c06 !important;
    }

    :where(.css-dev-only-do-not-override-1p3hq3p).ant-tabs .ant-tabs-ink-bar {
        background-color: #0a7c06;
    }

    div:where(.ant-tabs-tab-active) {
        background-color: #d5ebd4 !important;
    }

    .ant-tabs-tab {
        width: 200px
    }

    .ant-tabs-tab:hover {
        color: #0a7c06;
    }

    .ant-tabs-nav-list {
        height: 400px;
    }
}
</style>